#!/usr/bin/ruby
require "rubygems"
require "nokogiri"
require "open-uri"
require "iconv"
require "rbconfig"

require File.expand_path("../verycd_page", __FILE__)

class VeryCDAnalyzeJob
  VALID_VERYCD_URL_REGEXP = {
    :topic_url => /http:\/\/www\.verycd\.com\/topics\/\d+\//, 
    :entry_url => /http:\/\/www\.verycd\.com\/entries\/\d+\//
  }
  
  def initialize
    begin
      get_cmd_params
    rescue ArgumentError => e
      Debug::print_error e
    end
    @verified_urls = []
  end
  
  def go
    begin
      verify_urls
      @verified_urls.each { |url| VeryCDPage.new(url).analyze}
    rescue InvalidUrlError => e
      Debug::print_error e
    end
  end
  
  protected
    
  def get_cmd_params
    raise ArgumentError, "Please input a verycd url!" if ARGV.empty?
    @args = ARGV
  end
  
  def verify_urls
    @args.each { |arg| @verified_urls << arg if valid_url?(arg) }
    raise InvalidUrlError, "Please input a valid verycd url!" if @verified_urls.empty?
  end
  
  def valid_url?(url)
    VALID_VERYCD_URL_REGEXP.any? { |key, reg| reg =~ url}
  end
end

if __FILE__ == $0
  VeryCDAnalyzeJob.new.go
end